package com.jiahe.blog.utils;

import com.jiahe.blog.entity.UserAuthEntity;
import com.jiahe.blog.entity.UserInfoEntity;
import com.jiahe.blog.model.dto.UserInfoDTO;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 用户工具类
 */
public class UserUtils {

    /**
     * 获取当前登录用户
     *
     * @return 用户登录信息
     */
    public static UserInfoDTO getLoginUser(){
        return (UserInfoDTO) SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal();
    }

    /**
     * 封装用户登录信息
     *
     * @param userAuth           用户账号
     * @param userInfo       用户信息
     * @param articleLikeSet 点赞文章id集合
     * @param commentLikeSet 点赞评论id集合
     * @return 用户登录信息
     */
    public static UserInfoDTO convertLoginUser(UserAuthEntity userAuth, UserInfoEntity userInfo, List<String> roleList, Set<Integer> articleLikeSet, Set<Integer> commentLikeSet) {
        // 获取当前请求上下文
        HttpServletRequest request = ServletUtils.getRequest();
        String ipAddr = IpUtils.getIpAddr(request);
        String ipSource = IpUtils.getIpSource(ipAddr);
        String userAgent = UserAgentUtils.getUserAgent(request);
        // 封装权限集合
        return UserInfoDTO.builder()
                .id(userAuth.getId())
                .loginType(userAuth.getLoginType())
                .userInfoId(userInfo.getId())
                .username(userAuth.getUsername())
                .password(userAuth.getPassword())
                .disable(userAuth.getDisable())
                .email(userInfo.getEmail())
                .roleList(roleList)
                .nickname(userInfo.getNickname())
                .avatar(userInfo.getAvatar())
                .intro(userInfo.getIntro())
                .webSite(userInfo.getWebSite())
                .articleLikeSet(articleLikeSet)
                .commentLikeSet(commentLikeSet)
                .ipAddr(ipAddr)
                .ipSource(ipSource)
                .browser(UserAgentUtils.getBrowser(userAgent).getName())
                .os(UserAgentUtils.getOs(userAgent))
                .lastLoginTime(new Date())
                .build();
    }
}
